package com.template.app.common.service.parser;


import com.template.app.common.bean.UploadResult;
import com.template.app.common.enumerate.MaterialAddFlagEnum;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

//import com.contx.cssp.console.dsp.dao.SizeDictionaryDao;
//import com.contx.cssp.console.dsp.domain.SizeDictionary;

@Component
public abstract class MaterialParser{

    Logger logger = Logger.getLogger(getClass());

    public static final Long MAX_IMG = 2*1024 * 1024L;
    public static final Long MAX_SWF = 150 * 1024L;
    public static final Long MAX_PDF = 2*1024*2014L;

    protected static final String MULTIPLIE_SIGN = "x";

    @Value("${local_file_dir}")
    protected String localFileDir = null;

    @Value("${file_url_base}")
    protected String fileUrlBase = null;
    private Long sizeId;
    public abstract String getFileSize(String fileName, byte[] content, long fileLength) throws Exception;
    public abstract void addToResultList(String originalFileString,
                                         String parentFileName, byte[] content,
                                         long fileLength, List<UploadResult> resultList) throws IOException;

    public UploadResult wrapMaterialResult(String originalFileName,
                                                String parentFileName, byte[] content, long fileLength){
        UploadResult result = new UploadResult();
        result.setOriginalFilename(parentFileName + originalFileName);
        try{
            String fileType = getFileType(originalFileName);
            result.setFileType(fileType);
            result.setSizeDictionaryId(sizeId);
			result.setIsOK(MaterialAddFlagEnum.OK);
            String FileName = saveFileToHardDisk( content, fileType,localFileDir);
            result.setNewFilename(fileUrlBase+FileName);
        }catch(Exception e){
            logger.error(e);
			result.setIsOK(MaterialAddFlagEnum.ERROR);
            result.setReason(e.getLocalizedMessage());
        }
        return result;
    }

    //把文件保存在硬盘上
    private String  saveFileToHardDisk(byte[] content,String fileType,String fileDir) throws IOException{
        Date today = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat format1 = new SimpleDateFormat("yyyyMMddhhmmss");
        String random =String.valueOf(Math.random()).substring(2, 6);
        String resultFileName = "";
        // 保存文件到硬盘
        for (String filePath : fileDir.split(",")) {
            filePath += "/" + format.format(today);
            String fileName = filePath+"/"+format1.format(today)+random+"."+fileType;
            resultFileName = format.format(today)+"/"+format1.format(today)+random+"."+fileType;
            File file = new File(filePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            file = new File(fileName);
            file.createNewFile();


            OutputStream fileOutput = null;
            InputStream fileInputStream = null;
            try {
                fileOutput = new FileOutputStream(file);
                byte[] buffer = new byte[10000];
                fileInputStream = new ByteArrayInputStream(content);
                while(fileInputStream.read(buffer) > 0) {
                    fileOutput.write(buffer);
                }
            } catch (Exception e) {
                // TODO: handle exception
            }
            finally{
                fileOutput.flush();
                fileOutput.close();
            }
        }


        return resultFileName;
    }

    protected void saveFileFromInputStream(InputStream stream,String file) throws Exception{
        FileOutputStream fs = null;
        try{
            fs =new FileOutputStream(localFileDir + File.separator +file);
            IOUtils.copy(stream, fs);
        }finally{
            IOUtils.closeQuietly(fs);
        }
    }
    public String getFileType(String fileName) throws Exception{
        return fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
    }

}
